#!/bin/sh

set -u # Treat unset variables as an error.

tolower() {
    echo "$1" | tr '[:upper:]' '[:lower:]'
}

if is-bool-val-true "${CONTAINER_DEBUG:-0}"; then
    echo "--log-level"
    echo "debug"
fi

if is-bool-val-true "${WEB_FILE_MANAGER:-0}"; then
    echo "--enable-file-manager"

    ALLOWED_PATHS="$(mktemp)"
    DENIED_PATHS="$(mktemp)"

    # Add allowed paths.
    echo "${WEB_FILE_MANAGER_ALLOWED_PATHS:-AUTO}" | tr ',' '\n' | while read -r allowed_path; do
        [ -n "${allowed_path}" ] || continue

        if [ "$(tolower "${allowed_path}")" = "all" ]; then
            # Clear the file of allowed path and stop.
            echo > "${ALLOWED_PATHS}"
            break
        elif [ "$(tolower "${allowed_path}")" = "auto" ]; then
            # Some well-known paths that are allowed.
            for dir in /storage /output /config /tmp; do
                echo "${dir}" >> "${ALLOWED_PATHS}"
            done

            # Add volumes mapped to the container.
            awk '{print $3 " " $2}' < /proc/mounts | while read -r mount; do
                filesystem="$(echo "${mount}" | cut -d' ' -f1)"
                mountpoint="$(echo "${mount}" | cut -d' ' -f2-)"

                # Ignore mounts associated to system related file system types.
                case "${filesystem}" in
                    cgroup*) continue ;;
                    devpts) continue ;;
                    mqueue) continue ;;
                    proc) continue ;;
                    sysfs) continue ;;
                    tmpfs) continue ;;
                    *) ;;
                esac

                # Ignore mounts associated to system related paths.
                case "${mountpoint}" in
                    /) continue ;;
                    /dev | /dev/*) continue ;;
                    /etc | /etc/*) continue ;;
                    /proc | /proc/*) continue ;;
                    /sys | /sys/*) continue ;;
                    *) ;;
                esac

                echo "${mountpoint}" >> "${ALLOWED_PATHS}"
            done
        else
            echo "${allowed_path}" >> "${ALLOWED_PATHS}"
        fi
    done

    # Add denied paths.
    echo "${WEB_FILE_MANAGER_DENIED_PATHS:-}" | tr ',' '\n' | while read -r denied_path; do
        [ -n "${denied_path}" ] || continue
        echo "${denied_path}" >> "${DENIED_PATHS}"
    done

    # Print all arguments.
    sort -u < "${ALLOWED_PATHS}" | while read -r allowed_path; do
        [ -n "${allowed_path}" ] || continue
        echo "--allowed-path"
        echo "${allowed_path}"
    done
    sort -u < "${DENIED_PATHS}" | while read -r denied_path; do
        [ -n "${denied_path}" ] || continue
        echo "--denied-path"
        echo "${denied_path}"
    done

    rm "${ALLOWED_PATHS}"
    rm "${DENIED_PATHS}"
fi
